package com.shelpe.services.scheduler.item.adgroup;

import java.util.Calendar;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.batch.item.ItemProcessor;
import org.springframework.beans.factory.annotation.Autowired;

import com.shelpe.services.scheduler.dto.RptAdgroupDto;
import com.shelpe.services.scheduler.mongorepository.UnrecoverableErrorRepository;
import com.shelpe.services.scheduler.po.Adgroups;
import com.shelpe.services.scheduler.po.Campaigns;
import com.shelpe.services.scheduler.po.SyncLog;
import com.shelpe.services.scheduler.repository.AdgroupsRepository;
import com.shelpe.services.scheduler.syncclient.AdgroupClient;
import com.shelpe.services.scheduler.util.Util;

public class RptAdgroupProcessor  implements ItemProcessor<Campaigns, SyncLog>{

	private static final Logger logger = LoggerFactory.getLogger(AdgroupProcessor.class);
	
	@Autowired
	private AdgroupClient adClient;
	
	@Autowired
	private AdgroupsRepository adRep;
	
	@Autowired
	private UnrecoverableErrorRepository errorRep;
	
	@Override
	public SyncLog process(Campaigns item) throws Exception {
		// TODO Auto-generated method stub
		
		long userId = item.getUserId();
		if(errorRep.countByUserId(userId) > 0){
			return null;
		}
		
		return syncRptAdgroup(userId, item);
	}
	
	private SyncLog syncRptAdgroup(Long userId, Campaigns cam){
		
		if(!cam.getOnlineStatus().equalsIgnoreCase("online")){
			return null;
		}
		
		int addNum = 0;
		int updateNum = 0;
		int deleteNum = 0;
		long durTime = 0;
		long campaignId = cam.getCampaignId();
		RptAdgroupDto rptDto = new RptAdgroupDto();
		
		List<Adgroups> adList = adRep.findByCampaignId(campaignId);

		if(adList != null && adList.size() > 0){
			int pageSize = 10;
			int fromIndex = 0;
			int endIndex = 0;
			Calendar cal = Calendar.getInstance();	  
			int hour=cal.get(Calendar.HOUR_OF_DAY);//小时	
			String record = hour > 8 ? "no" : "yes";
			
			do{
				endIndex += pageSize; 
				if(endIndex > adList.size()){
					endIndex = adList.size();
				}
				
				StringBuilder sb = new StringBuilder();
				int index = fromIndex;
				for(; index < endIndex-1; index++){
					sb.append(adList.get(index).getAdgroupId());
					sb.append(",");
				}
				sb.append(adList.get(index).getAdgroupId());
				rptDto = adClient.syncRptAdgroupsByUserAd(userId, campaignId, sb.toString(), record);
				addNum += rptDto.getAddNum();
				updateNum += rptDto.getUpdateNum();
				deleteNum += rptDto.getDeleteNum();
				durTime += rptDto.getDurTime();
				fromIndex += pageSize; 
				//logger.info("userId {}, campaignId {}, addNum {}, durTime {}", userId, campaignId, rptDto.getAddNum(), rptDto.getDurTime());
			}while(fromIndex < adList.size());	
		}	
		
		rptDto.setAddNum(addNum);
		rptDto.setUpdateNum(updateNum);
		rptDto.setDeleteNum(deleteNum);
		rptDto.setDurTime(durTime);
		
		return Util.convert(rptDto);	
	}
}
